package com.dpj.nio.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class TestByteBuffer {
    public static void main(String[] args) throws FileNotFoundException {
        //FileChannel
        //1.输入输出流 2.RandomAccessFile
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            //划分内存空间作为缓冲区
            ByteBuffer buffer=ByteBuffer.allocate(10);
            while (true){
                //从channel 读取数据，向 buffer写入
                int len = channel.read(buffer);
                log.debug("读取到的字节为数{}",len);
                if(len==-1){
                    break;
                }
                //打印buffer内容
                buffer.flip(); //切换至读模式
                while(buffer.hasRemaining()){
                    byte b = buffer.get();
                    log.debug("读取到的字节为{}",(char) b);

                }
                //切换为写模式
                buffer.clear();
            }
        } catch (IOException e) {
        }

    }
}
